//
//  ProductController.swift
//  baihuiju
//
//  Created by 赵家彬 on 2018/5/27.
//  Copyright © 2018年 赵家彬. All rights reserved.
//

import UIKit
import RxSwift
import FSPagerView
import WebKit

class ProductController: CBBaseViewController {
    
    var scrollView:UIScrollView!
    
    var pageView:FSPagerView!
    var vwProductContent:ProductContentView!
    var vwWebProductDetail:WKWebView!
    var model:CommodityModel!
    var arrImageUrl:[String] = [String]()
    let BANNER_CELL_ID = "COMMODITY_CELL_ID"
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor(hex:0xf2f2f2)
        self.title = "商品详情"
        
        scrollView = UIScrollView()
        scrollView.showsVerticalScrollIndicator = false
        scrollView.showsHorizontalScrollIndicator = false
        self.view.addSubview(scrollView)
        scrollView.snp.makeConstraints { (make) in
            make.left.equalToSuperview()
            make.top.equalToSuperview()
            make.right.equalToSuperview()
            make.bottom.equalToSuperview()
        }
        
        pageView = FSPagerView(frame: .zero)
        pageView.dataSource = self
        pageView.register(FSPagerViewCell.self, forCellWithReuseIdentifier: BANNER_CELL_ID)
        pageView.automaticSlidingInterval = 3.0
        scrollView.addSubview(pageView)
        pageView.snp.makeConstraints { (make) in
            make.left.equalToSuperview()
            make.top.equalToSuperview().offset(-1 * SB_HT)
            make.width.equalToSuperview()
            make.height.equalTo(267)
        }

        vwProductContent = (Bundle.main.loadNibNamed("ProductContentView", owner: nil, options: nil)?.first as? ProductContentView) ?? ProductContentView()
        scrollView.addSubview(vwProductContent)
        vwProductContent.snp.makeConstraints { (make) in
            make.left.equalToSuperview()
            make.top.equalTo(pageView.snp.bottom)
            make.width.equalToSuperview()
        }
        
        
        let configuration = WKWebViewConfiguration()
        configuration.preferences = WKPreferences()
        configuration.preferences.javaScriptEnabled = true
        configuration.processPool = WKProcessPool()
        configuration.userContentController = WKUserContentController()
        configuration.userContentController.add(self, name: "sendHeight")
        
        vwWebProductDetail = WKWebView(frame: .zero, configuration: configuration)
        vwWebProductDetail.navigationDelegate = self
        vwWebProductDetail.uiDelegate = self
        vwWebProductDetail.autoresizingMask = .flexibleHeight
        vwWebProductDetail.scrollView.isScrollEnabled = false
        vwWebProductDetail.scrollView.bounces = false
        let request = URLRequest(url: URL(string: ActionURL.WEB_COMMODITY_DETAIL + "?goods_id=\(model.id)")!)
        print(ActionURL.WEB_COMMODITY_DETAIL + "?goods_id=\(model.id)")
        vwWebProductDetail.load(request)
        scrollView.addSubview(vwWebProductDetail)
        vwWebProductDetail.snp.makeConstraints { (make) in
            make.left.equalToSuperview()
            make.top.equalTo(vwProductContent.snp.bottom)
            make.width.equalToSuperview()
            make.height.equalTo(500)
            make.bottom.equalToSuperview()
        }
        
        initData()
    }
    
    func initData() {
        NetworkTool.requestData(url: ActionURL.GET_COMMODITY_DETAIL, param: ["goods_id":model.id,"isApp":1])
            .map { (json) -> CommodityDetailModel? in
                SVProgressHUD.show()
                return CommodityDetailModel.mj_object(withKeyValues: json["rows"].dictionaryObject)
            }.catchErrorJustReturn(nil)
            .observeOn(MainScheduler.instance)
            .subscribe(onNext:{ [unowned self] opDetailModel in
                SVProgressHUD.dismiss()
                if let tpModel = opDetailModel {
                    self.flushView(model: tpModel)
                }
            }).disposed(by: disposeBag)
    }
    
    func flushView(model:CommodityDetailModel) {
        self.arrImageUrl = model.img.components(separatedBy: ",").map { ActionURL.HOST + $0 }
        self.pageView.reloadData()
        vwProductContent.model = model
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.tabBarController?.tabBar.isHidden = true
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.tabBarController?.tabBar.isHidden = false
    }
    
    
}

extension ProductController: UIWebViewDelegate, WKNavigationDelegate, WKUIDelegate,WKScriptMessageHandler {
    
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        let msgBody = message.body as? String ?? ""
        switch message.name {
        case "sendHeight":
            let newHt = (Double(msgBody) ?? 0.0).cg
            if newHt > 500 {
                vwWebProductDetail.snp.updateConstraints({ (make) in
                    make.height.equalTo((Double(msgBody) ?? 0.0).cg)
                })
            }
            break;
        default:
            break;
        }
    }
    
    // 加载完成的代理方法
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        print("hello")
    }
    
    //兼容Alert
    //Alert弹框
    func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
        let alert = UIAlertController(title: message, message: nil, preferredStyle: UIAlertControllerStyle.alert)
        let action = UIAlertAction(title: "好的", style: UIAlertActionStyle.cancel) { (_) in
            completionHandler()
        }
        alert.addAction(action)
        present(alert, animated: true, completion: nil)
    }
    //confirm弹框
    func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) {
        let alert = UIAlertController(title: message, message: nil, preferredStyle: UIAlertControllerStyle.alert)
        let action = UIAlertAction(title: "确定", style: UIAlertActionStyle.default) { (_) in
            completionHandler(true)
        }
        let cancelAction = UIAlertAction(title: "取消", style: UIAlertActionStyle.cancel) { (_) in
            completionHandler(false)
        }
        alert.addAction(action)
        alert.addAction(cancelAction)
        present(alert, animated: true, completion: nil)
    }
    //TextInput弹框
    func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void) {
        let alert = UIAlertController(title: "", message: nil, preferredStyle: UIAlertControllerStyle.alert)
        alert.addTextField { (_) in}
        let action = UIAlertAction(title: "确定", style: UIAlertActionStyle.default) { (_) in
            completionHandler(alert.textFields?.last?.text)
        }
        alert.addAction(action)
        present(alert, animated: true, completion: nil)
    }
    
}

extension ProductController: FSPagerViewDataSource {
    
    func numberOfItems(in pagerView: FSPagerView) -> Int {
        return arrImageUrl.count
    }
    
    func pagerView(_ pagerView: FSPagerView, cellForItemAt index: Int) -> FSPagerViewCell {
        let cell = pagerView.dequeueReusableCell(withReuseIdentifier: BANNER_CELL_ID, at: index)
        cell.imageView?.kf.setImage(with: URL(string: arrImageUrl[index]), placeholder: UIImage(named: "bg_place_holder"), completionHandler: nil)
        return cell
    }
    
    
}
